package com.ruoyi.system.netty;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TbDevice;
import com.ruoyi.system.service.ITbRoomDeviceService;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * 自定义助手类
 */
@Slf4j
@ChannelHandler.Sharable
@Component
public class CustomHandler extends SimpleChannelInboundHandler<String> {

    @Autowired
    ITbRoomDeviceService tbRoomDeviceService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        // 获取 Channel
        Channel channel = ctx.channel();
        // 获取远程地址
        InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
        // 提取 IP 地址字符串
        String clientIP = remoteAddress.getAddress().getHostAddress();
        System.out.println("客户端 IP: " + clientIP);
        log.info("tcp消息 ::{}", msg);
        try {
            JSONObject jsonObject1 = JSONObject.parseObject(msg);
            String cmd = jsonObject1.getString("cmd");
            if (StringUtils.isEmpty(cmd)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("cmd", "error no cmd");
                ByteBuf buffer = Unpooled.copiedBuffer(jsonObject.toString(), CharsetUtil.UTF_8);
                ctx.writeAndFlush(buffer);
            }
            // 注册
            if ("register".equals(cmd)) {
                String ip = jsonObject1.getString("ip");
                TbDevice device = tbRoomDeviceService.getDevice(ip);
                if (device == null) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("cmd", "register");
                    jsonObject.put("is_succeed", false);
                    jsonObject.put("message", "no ip");
                    JSONObject jsonObject2 = new JSONObject();
                    jsonObject2.put("device-id", null);
                    jsonObject.put("data", jsonObject2);
                    ByteBuf buffer = Unpooled.copiedBuffer(jsonObject.toString(), CharsetUtil.UTF_8);
                    ctx.writeAndFlush(buffer);
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("cmd", "register");
                jsonObject.put("is_succeed", true);
                jsonObject.put("message", "ok");
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("device-id", device.getId());
                jsonObject.put("data", jsonObject2);
                NettyTcpServer.deviceChannelMap.put(String.valueOf(device.getId()), ctx.channel());
                ByteBuf buffer = Unpooled.copiedBuffer(jsonObject.toString(), CharsetUtil.UTF_8);
                ctx.writeAndFlush(buffer);
            }
            if ("user-login".equals(cmd)) {
                String deviceid = jsonObject1.getString("device-id");
                SysUser sysUser = tbRoomDeviceService.tcpUserLogin(jsonObject1);
                if (sysUser == null) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("cmd", "user-login");
                    jsonObject.put("is_succeed", false);
                    jsonObject.put("message", "login error");
                    JSONObject jsonObject2 = new JSONObject();
                    jsonObject2.put("user-id", null);
                    jsonObject.put("data", jsonObject2);
                    ByteBuf buffer = Unpooled.copiedBuffer(jsonObject.toString(), CharsetUtil.UTF_8);
                    ctx.writeAndFlush(buffer);
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("cmd", "user-login");
                jsonObject.put("is_succeed", true);
                jsonObject.put("message", "ok");
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("user-id", sysUser.getUserId());
                jsonObject.put("data", jsonObject2);
                ByteBuf buffer = Unpooled.copiedBuffer(jsonObject.toString(), CharsetUtil.UTF_8);
                ctx.writeAndFlush(buffer);
                NettyTcpServer.deviceUserChannelMap.put(String.valueOf(deviceid), sysUser);
                NettyTcpServer.userNameDeviceChannelMap.put(sysUser.getUserName(), String.valueOf(deviceid));
            }
            if ("user-logout".equals(cmd)) {
                String user = jsonObject1.getString("user");
                String s = NettyTcpServer.userNameDeviceChannelMap.get(user);
                NettyTcpServer.userNameDeviceChannelMap.remove(user);
                NettyTcpServer.deviceChannelMap.remove(s);
                NettyTcpServer.deviceUserChannelMap.remove(s);

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("cmd", "user-login");
                jsonObject.put("is_succeed", true);
                jsonObject.put("message", "ok");
                JSONObject jsonObject2 = new JSONObject();
                jsonObject.put("data", jsonObject2);
                ByteBuf buffer = Unpooled.copiedBuffer(jsonObject.toString(), CharsetUtil.UTF_8);
                ctx.writeAndFlush(buffer);
            }
            tbRoomDeviceService.dosomething(msg, clientIP);
        } catch (Exception e) {
            log.error("ue数据处理异常{}", e);
        }
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        // 获取 Channel
        Channel channel = ctx.channel();
        // 获取远程地址
        InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
        // 提取 IP 地址字符串
        String clientIP = remoteAddress.getAddress().getHostAddress();
        System.out.println("channel 注册 客户端 IP: " + clientIP);
        try {
            JSONObject jsonObject = tbRoomDeviceService.getSt(clientIP);
            ByteBuf buffer = Unpooled.copiedBuffer(jsonObject.toString(), CharsetUtil.UTF_8);
            ctx.writeAndFlush(buffer);
        } catch (Exception e) {
            log.error("ue数据处理异常{}", e);
        }

    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 移除");
        // 获取 Channel
        Channel channel = ctx.channel();
        // 获取远程地址
        InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
        // 提取 IP 地址字符串
        String clientIP = remoteAddress.getAddress().getHostAddress();
        System.out.println("channel 移除 客户端 IP: " + clientIP);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 活跃");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel不活跃");
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("助手类添加");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("助手类移除");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 读取完毕");
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println("用户事件触发");
    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {
        System.out.println("channel 可写更改");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("捕获到异常");
    }
}


